package pl.edu.pjwstk.kor.web.controller;

import java.util.Collection;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Maps;

import pl.edu.pjwstk.kor.model.Customer;
import pl.edu.pjwstk.kor.model.Deal;
import pl.edu.pjwstk.kor.model.Rank;
import pl.edu.pjwstk.kor.sbql4j.project2.Project2Query;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/p2")
public class Queries2 {
	@Autowired private Project2Query p2q;
	
	@RequestMapping("/main.html")
	public ModelAndView main(HttpServletRequest request) {
		int q1DealCount = ServletRequestUtils.getIntParameter(request, "q1DealCount", 7);
		String q2StreetName = ServletRequestUtils.getStringParameter(request, "q2StreetName", "Jasna");
		String q3JobName = ServletRequestUtils.getStringParameter(request, "q3Job", "szef");
		int q3Yer = ServletRequestUtils.getIntParameter(request, "q3Year", 2010);
		double q4Cost = ServletRequestUtils.getDoubleParameter(request, "q4Cost", 1000);
		double q5Cost = ServletRequestUtils.getDoubleParameter(request, "q5Cost", 2100000);

		Collection<Rank> ranks = p2q.query5(q5Cost);
		Map<String, Double> rankCost = Maps.newHashMap();
		for(Rank r : ranks) {
			double cost = 0.0;
			for(Customer c : r.getCustomers()) {
				for(Deal d : c.getDeals()) {
					cost += d.getCost();
				}
			}
			rankCost.put(r.getGroupName(), cost);
		}


		return new ModelAndView("/p2/main")
			.addObject("q1", p2q.query1(q1DealCount))
				.addObject("q1DealCount", q1DealCount)
			.addObject("q2", p2q.query2(q2StreetName))
				.addObject("q2StreetName", q2StreetName)
			.addObject("q3", p2q.query3(q3JobName, q3Yer))
				.addObject("q3Job", q3JobName)
				.addObject("q3Year", q3Yer)
			.addObject("q4", p2q.query4(q4Cost))
				.addObject("q4Cost", q4Cost)
			.addObject("q5", p2q.query5(q5Cost))
				.addObject("q5a", rankCost)
				.addObject("q5Cost", q5Cost)
			.addObject("q6", p2q.query6())
			.addObject("q7", p2q.query7())
			;
	}
}

